# -*- coding: utf-8 -*-
"""
 @Time    : 2021/1/18 下午5:59
 @Author  : tgy
 你有一个字典列表，你想根据某个或某几个字典字段来排序这个列表。

 callable

"""

rows = [
    {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
    {'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
    {'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
    {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]


class myItemGetter:
    ...
    __slots__ = ['_items', '_call']

    def __init__(self, item, *items):
        ...
        if not items:
            self._items = (item,)
            def func(obj):
                ...
                return obj[item]
            self._call = func
        else:
            self._items = (item,) + items
            def func(obj):
                return tuple(obj[x] for x in self._items)
            self._call = func

    def __call__(self, obj):
        return self._call(obj)


from operator import itemgetter


def test01():
    ...
    uid_sort = sorted(rows, key=myItemGetter('uid'))
    fname_sort = sorted(rows, key=itemgetter('fname'))
    print(uid_sort, fname_sort, sep='\n')
    uid_fname_sort = sorted(rows, key=myItemGetter('uid', 'fname'))
    print(uid_fname_sort)


def test02():
    ...
    uid_fname_sort = sorted(rows, key=lambda x: (x['uid'], x['fname']))
    print(uid_fname_sort)


if __name__ == '__main__':
    ...
    test01()
